package com.classtwo.colleage.controler;


import com.classtwo.colleage.conf.DatabaseUser_attendanceInfo;
import com.classtwo.colleage.conf.DatabaseUser_classInfo;
import com.classtwo.colleage.conf.DatabaseStudentInfo;
import com.classtwo.colleage.model.Student;
import com.classtwo.colleage.model.User_attendance;
import com.classtwo.colleage.model.User_class;
import com.classtwo.colleage.service.IFileToExcelService;
import com.classtwo.colleage.service.IFileUploadService;
import com.classtwo.colleage.vo.StudentVo;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

/**
 * 主页页面控制器
 */
@Controller

public class FileUpControler {
    @Autowired
    private IFileToExcelService iFileToExcelService;
    @Autowired
    private IFileUploadService iFileUploadService;
    @Autowired
    private DatabaseUser_classInfo classInfo;
    @Autowired
    private DatabaseStudentInfo studentInfo;
    @Autowired
    private DatabaseUser_attendanceInfo user_attendanceInfo;



    /*    private static final Logger log = (Logger) LoggerFactory.getLogger(FileUpControler.class);*/

    @RequestMapping(value = "/upload")
    @ResponseBody
    public List<StudentVo> upload(@RequestParam("file") MultipartFile file, String classnodeUpload, String classnameUpload, String usernameUpload) {
        List<User_class> studentList = new ArrayList<>();
        HttpSession httpSession;
        List<StudentVo> studentVos = new ArrayList<>();
        String path=iFileUploadService.upload(file);
        studentList = iFileToExcelService.importExcel(path,classnodeUpload,classnameUpload);
        for(User_class studata:studentList){
            if (studata.getUsername() != null) {
                classInfo.save(studata);
                //班级数量加一
                List<User_class> list = classInfo.findAllByClassnode(classnodeUpload);
                for (User_class classdata : list) {
                    //班级人数加1
                    classdata.setClassnumber(classdata.getClassnumber() + 1);
                    classInfo.save(classdata);
                }
                //默认考勤日期
                User_class FirstData = classInfo.findFirstByClassnodeAndUsertype(classnodeUpload, "学生");
                Student student = studentInfo.findFirstByUsername(studata.getUsername());
                if (FirstData == null) {
                    for (int i = 0; i < 4; i++) {
                        //当前时间
                        String TimeNow = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
                        User_attendance user_data = new User_attendance();
                        user_data.setAttendance((i + 1) + TimeNow);
                        user_data.setClassnode(classnodeUpload);
                        user_data.setName(studata.getName());
                        user_data.setStatus("1");
                        user_data.setStudentnumber(student.getStudentnumber());
                        user_data.setUsername(studata.getUsername());
                        user_attendanceInfo.save(user_data);
                    }
                } else {
                    List<User_attendance> list1 = user_attendanceInfo.findAllByUsernameAndClassnode(FirstData.getUsername(),classnodeUpload);
                    for (User_attendance data3 : list1) {
                        User_attendance user_data = new User_attendance();
                        user_data.setAttendance(data3.getAttendance());
                        user_data.setClassnode(data3.getClassnode());
                        user_data.setName(studata.getName());
                        user_data.setStatus("1");
                        user_data.setStudentnumber(student.getStudentnumber());
                        user_data.setUsername(studata.getUsername());
                        user_attendanceInfo.save(user_data);
                    }
                }
                studentVos.add(new StudentVo("已注册", studata));
            }
            else {
                studentVos.add(new StudentVo("未注册",studata));
            }



        }

        return studentVos;
        /* return "redirect:/Teacher/login/TeacherExam/loginUser/content?classnode="+classnodeUpload;*/




    }


     /*   try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
          *//*  log.info("上传的文件名为：" + fileName);*//*
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
        *//*    log.info("文件的后缀名为：" + suffixName);*//*
            // 设置文件存储路径
            String filePath = "E://";
            String path = filePath + fileName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入


            iFileToExcelService.importExcel(path);

            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }*/

    /*@PostMapping("/batch")
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String filePath = "/Users/dalaoyang/Downloads/";
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath + file.getOriginalFilename())));//设置文件路径及名字
                    stream.write(bytes);// 写入
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "第 " + i + " 个文件上传失败 ==> "
                            + e.getMessage();
                }
            } else {
                return "第 " + i
                        + " 个文件上传失败因为文件为空";
            }
        }
        return "上传成功";
    }*/




}
